package com.samuel.blog.service.impl;

import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.dao.JurisdictionDao;
import com.samuel.blog.entity.JurisdictionEntity;
import com.samuel.blog.service.JurisdictionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kaiji
 */
@Transactional
@Service("jurisdictionService")
public class JurisdictionServiceImpl extends BaseServiceImpl<JurisdictionEntity, String> implements JurisdictionService {
	
	@Resource
	private JurisdictionDao jurisdictionDao;
	
	@Override
    public List<JurisdictionEntity> selectByTop() {
		Map<String, Object> map = new HashMap<>();
		map.put("parentId", "0");
		List<JurisdictionEntity> selectByMap = this.selectByMap(map);
		if (null != selectByMap) {
			for (JurisdictionEntity jurisdictionEntity : selectByMap) {
				map.put("parentId", jurisdictionEntity.getJurisdictionId());
				List<JurisdictionEntity> childs = this.selectByMap(map);
				jurisdictionEntity.setChilds(childs);
			}
		}
		return selectByMap;
	}

	@Override
	public List<JurisdictionEntity> selectByRoleId(String roleId) {
		List<JurisdictionEntity> list = jurisdictionDao.selectByRoleId(roleId);
		return null == list || list.size() <= 0 ? null : list;
	}

	@Override
	public JurisdictionEntity selectByCode(String code) {
		Map<String, Object> map = new HashMap<>();
		map.put("code", code);
		List<JurisdictionEntity> jurList = selectByMap(map);
		return null != jurList ? jurList.get(0) : null;
	}

	@Override
	public int delete(String[] ids) {
		try {
			// 1. 根据id 查询角色与权限的中间表 然后删除数据
			jurisdictionDao.deleteRoleAndJurisdiction(ids);
			// 2. 删除权限
			for (String id : ids) {
				jurisdictionDao.deleteByPrimaryKey(id);
			}
			
			return CommonConstant.NoticeCode.SUCCESS_ONE;
		} catch (Exception e) {
			e.printStackTrace();
			return CommonConstant.NoticeCode.ERROR_ZERO;
		}
	}

}
